<template>
	<scroll-view class="container" scroll-y="true">
		<uni-popup ref="popup" type="bottom">
			<assess-save-view :evaluateRecordId="evaluateRecordId" :QRCodeSrc="QRCodeSrc" :parentGranted="assessDetailEntity.parentGranted" @closeClick="shareCancel" ></assess-save-view>
		</uni-popup>
		<uni-popup ref="popupConpare" type="dialog">
			<assess-compare-view :assessList="assessList" :evaluateRecordId="evaluateRecordId" @compareClick="compareHideClick"></assess-compare-view>
		</uni-popup>

		<assess-children-view v-if="hasData" :name="name" :gender="gender" :month="month" :height="height" :weight="weight"/>

		<view class="view">

			<view class="suggest" :class="paid?'':'mask'">
				<view style="margin-top: 20rpx">
					<bmi-view v-if="hasData" forceUseOldCanvas="forceUseOldCanvas" :bmi="assessDetailEntity.bmi" :name="name" :gender="gender" :height="height" :weight="weight" :birthday="birthday"></bmi-view>
				</view>
				
				<view style="padding: 40rpx;background-color: #FFFFFF;margin-top: 10px;">
					<scoresview v-if="hasData" :dimensionScores="assessDetailEntity.dimensionScores" :wisdomAge="wisdomAge" :dqFraction="dqFraction" :level="level"></scoresview>
				</view>
				
				<view class="scores-bar">
					<!-- #ifdef MP -->
					<assessScoresEchart v-if="hasData" :useOldCanvas="forceUseOldCanvas" :evaluatingDate="assessDetailEntity.evaluatingDate" :dimensionScores="assessDetailEntity.dimensionScores"></assessScoresEchart>
					<!-- #endif -->
					<!-- #ifndef MP -->
					<scoresbar v-if="hasData" :dimensionScores="assessDetailEntity.dimensionScores"></scoresbar>
					<!-- #endif -->
				</view>
				
				<view class="suggest-title">
					评估建议{{paid?'':''}}
					<view class="conclusion" v-if="normalConclusion!=null">{{normalConclusion}}</view>
					<view class="conclusion" v-if="warningConclusion!=null">{{warningConclusion}}</view>
				</view>
				
				<assess-high-level v-if="hasData"
								   :paid="paid"
								   :high-level-info="assessDetailEntity.highLevelInfo"
								   :answer-sheet="assessDetailEntity.answerSheet"/>

				<view style="align-self: flex-start;margin-top: 20rpx;">*此测评报告非正式的医学诊断结果，仅供参考</view>
				
				<view v-if="isShared !='true'" style="display: flex;flex-direction: row;justify-content: center">
					<view v-if="appId !== 'wx8033fe9de99c902d'" class="assess-result-share" @click="shareClick">保存</view>
					<view v-if="appId !== 'wx8033fe9de99c902d'" class="assess-result-share" style="margin-left: 20rpx;" @click="compareClick">对比</view>
					<view v-if="appId !=='wx785122fc0f5d90fd' && appId !== 'wx6d897a71f2f75579' && appId !== 'wxf11d82eb1a38ad9e'" class="assess-result-share" style="margin-left: 20rpx;" @click="publishClick(1)">推送给家长</view>
					<view v-if="appId === 'wx8033fe9de99c902d' && scene === 1037" class="assess-result-share" style="margin-left: 20rpx;" @click="backClick">返回</view>
				</view>
				<view class="safe-area-view"></view>
			</view>
			<view v-if="!paid && hasData" class="suggest-buy">
				<powerView class="power" :evaluateRecordId="evaluateRecordId"></powerView>
				<view v-if="restCount>0">
					<button class="suggest-buy-btn" @click="payRecord()">
						解锁测评
					</button>
				</view>
				<view v-else>
					<button v-if="isInput" class="suggest-buy-btn" @click="vipPay()">
						仅限合作机构查看
					</button>
					<button v-if="!isInput" class="suggest-buy-btn" open-type="getPhoneNumber" @getphonenumber="getphonenumber">
						仅限合作机构查看
					</button>
				</view>
				<view v-if="isShared !='true'" style="display: flex;flex-direction: row;">
					<view v-if="appId !=='wx785122fc0f5d90fd' && appId !== 'wx6d897a71f2f75579' && appId !== 'wxf11d82eb1a38ad9e'" class="assess-result-share" style="margin-left: 20rpx;" @click="publishClick(0)">推送给家长</view>
					<view v-if="appId === 'wx8033fe9de99c902d' && scene === 1037" class="assess-result-share" style="margin-left: 20rpx;" @click="backClick">返回</view>
				</view>
			</view>
		</view>
	</scroll-view>
</template>

<script>
	import scoresbar from '../../../components/assess-scores-bar.vue'
	import assessScoresEchart from '../../../components/assess-scores-echart.vue'
	import scoresview from '../../../components/assess-scores-view.vue'
	import AssessHighLevel from  '../../../components/assess-high-level.vue'

	import uniPopup from '@/components/uni-popup/uni-popup.vue'
	import uniPopupMessage from '@/components/uni-popup/uni-popup-message.vue'
	import uniPopupDialog from '@/components/uni-popup/uni-popup-dialog.vue'

	import powerView from '../../../components/power-view.vue'
	import bmiView from '../../../components/assess-bmi-view.vue'
	import AssessCompareView from '@/components/assess-compare-view.vue'
	import AssessChildrenView from '@/components/assess-children-view.vue'
	import AssessSaveView from '@/components/assess-save-view.vue'

	import utils from '../../../utils/utils.js'

	var _self;
	var canvaColumn = null;

	export default {
		components: {
			scoresbar,
			assessScoresEchart,
			scoresview,

			uniPopup,
			uniPopupMessage,
			uniPopupDialog,

			powerView,
			bmiView,
			AssessHighLevel,
			AssessCompareView,
			AssessChildrenView,
			AssessSaveView
		},

		data() {
			return {
				evaluateRecordId: '',
				hasData: false,

				assessDetailEntity: {
					dimensionScores: [],
					answerSheet: [],
					parentGranted: true,
				},
				name: '',
				month: '',
				gender: 1,
				height: '',
				weight: '',
				birthday: '',

				wisdomAge: '',
				dqFraction: 0,
				level: '',
				suggest: '',
				warningConclusion: '',
				normalConclusion: '',

				///是否购买
				paid: false,

				QRCodeSrc: '',

				///是否分享
				isShared: 'false',
				///手机是否已保存
				isInput: false,

				///会员次数
				restCount: 0,

				assessList: [],

				theme: getApp().globalData.theme,
				appId: getApp().globalData.appid,
				scene: 0,
				
				forceUseOldCanvas: false,
			}
		},

		onLoad(option) {
			_self = this;
			// #ifdef MP
				var obj = wx.getLaunchOptionsSync();
				this.scene = obj.scene;
				console.log(obj);
			// #endif

			console.log(this.appId);
			this.evaluateRecordId = option.evaluateRecordId;
			this.isShared = option.isShared;
			console.log(option);
			this.check = true;
			
			try {
				const res = uni.getSystemInfoSync();
				console.log(res.platform);
				if (res.platform === 'windows' || res.platform === 'mac') {
					this.forceUseOldCanvas = true;
				}
			} catch (e) {
				// error
			}

			uni.getStorage({
				key: 'mailAddress',
				success: function(res) {
					_self.mailAddress = res.data
				}
			});
			if (!utils.isEmpty(getApp().globalData.user.mobile)) {
				this.isInput = true;
			}
			this.restCount = getApp().globalData.user.org.restCount;

			uni.hideShareMenu({})
		},

		onShow() {
			if (this.appId === 'wx8033fe9de99c902d') {
				uni.hideHomeButton();
			}
			if (this.isShared === 'true') {
				this.getSharedDetail();
			} else {
				this.getAssessDetail();
			}
			// this.getSharedDetail();
		},

		methods: {
			getAssessDetail() {
				uni.showLoading({})
				var p = {
					evaluateRecordId: this.evaluateRecordId,
				}
				console.log('params');
				console.log(p);
				this.$http.post('/eapi/operator/detail', {}, {
					params: p
				}).then(res => {
					uni.hideLoading()
					console.log(res);
					if (res.code === '000000') {
						this.handleData(res.data)
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				}).catch(err => {
					uni.hideLoading()
					uni.showToast({
						title: err,
						icon: 'none'
					})
				});
			},

			getSharedDetail() {
				uni.showLoading({})
				this.$http.post('/eapi/manager/detail', {}, {
					params: {
						evaluateRecordId: this.evaluateRecordId,
					}
				}).then(res => {
					uni.hideLoading()
					console.log(res);
					if (res.code === '000000') {
						this.handleData(res.data)
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				}).catch(err => {
					uni.hideLoading()
					uni.showToast({
						title: err,
						icon: 'none'
					})
				});
			},

			handleData(data) {
				this.name = data.childrenName;
				this.month = data.month;
				this.gender = data.gender;
				this.height = data.height;
				this.weight = data.weight;
				var date = utils.formatISODate(data.birthday);
				this.birthday = utils.formatDate(date, 'yyyy-MM-dd');
				this.paid = data.paid;
				// this.paid = true;

				var month = data.month;

				var dqTotal = 0.0;
				var monthTotal = 0.0;
				var size = 0;
				for (var index in data.dimensionScores) {
					var item = data.dimensionScores[index];

					item.month = item.month / 10;
					item.dqFraction = item.dq / 10;

					if (item.dimensionName === '交流互动警示行为') {
						item.dimensionNamev2 = "警示\n行为";
					} else if (item.dimensionName === '精细动作') {
						item.dimensionNamev2 = '精细\n动作'
					} else if (item.dimensionName === '适应能力') {
						item.dimensionNamev2 = '适应\n能力'
					} else if (item.dimensionName === '社会行为') {
						item.dimensionNamev2 = '社会\n行为'
					} else if (item.dimensionName === '警示行为') {
						item.dimensionNamev2 = '警示\n行为'
					} else {
						item.dimensionNamev2 = item.dimensionName;
					}

					if (item.dimensionName != '交流互动警示行为') {
						dqTotal += item.dqFraction;
						monthTotal += item.month;
						size += 1;
					}
				}

				var wisdomAge = monthTotal / size;
				var dqFraction = dqTotal / size;

				var level = '';
				if (dqFraction >= 130) {
					level = '超常';
				} else if (dqFraction >= 115) {
					level = '优秀';
				} else if (dqFraction >= 85) {
					level = '正常';
				} else if (dqFraction >= 70) {
					level = '落后';
				} else {
					level = '偏低';
				}

				var suggest = '';
				for (var index in data.failedQuestions) {
					var item = data.failedQuestions[index];
					if (item.month <= month) {
						suggest = suggest + '\n' + item.title + "\n" + item.advise + "\n";
					}
				}

				this.warningConclusion = data.warningConclusion;
				this.normalConclusion = data.normalConclusion;
				this.assessDetailEntity = data;
				this.wisdomAge = wisdomAge;
				this.dqFraction = dqFraction;
				this.level = level;
				this.suggest = suggest;
				this.published = data.published;
				this.hasData = true;
			},

			vipPay() {
				uni.navigateTo({
					url: '/pages-assess/vip-pay/vip-pay?evaluateRecordId=' + this.evaluateRecordId
				})
			},

			shareClick() {
				if (this.paid) {
					if (this.QRCodeSrc === '') {
						this.getReportShareUrl(true)
					} else {
						this.$refs.popup.open()
					}
				}
			},

			shareCancel() {
				this.$refs.popup.close()
			},

			///获取二维码地址
			getReportShareUrl(openPopup) {
				uni.showLoading()
				var p = {
					evaluateRecordId: this.evaluateRecordId,
				}
				this.$http.request({
					method: 'GET',
					url: '/eapi/operator/report_shared_url',
					params: p,
				}).then(res => {
					uni.hideLoading()
					console.log(res);
					if (res.code === '000000') {
						this.sharedUrl = res.data.url;
						this.QRCodeSrc = res.data.qrcode;
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
					if (openPopup) {
						this.$refs.popup.open()
					}
				}).catch(err => {
					uni.hideLoading()
					if (openPopup) {
						this.$refs.popup.open()
					}
				})
			},

			getphonenumber(e) {
				console.log(e);
				if (e.detail.errMsg == "getPhoneNumber:ok") {
					this.getPhone(e.detail.encryptedData, e.detail.iv)
				} else {
					uni.showToast({
						title: '获取手机失败!',
						icon: 'none'
					})
				}
			},

			getPhone(encryptedData, iv) {
				console.log(encryptedData);
				console.log(iv);
				console.log(getApp().globalData.session.sessionKey);
				uni.showLoading({})
				this.$http.request({
					method: 'GET',
					url: '/wx/user/' + getApp().globalData.appid + '/wxphone',
					data: {
						appid: getApp().globalData.appid,
						encryptedData: encryptedData,
						iv: iv,
						sessionKey: getApp().globalData.session.sessionKey,
					}
				}).then(res => {
					console.log(res);
					uni.hideLoading();
					if (res.code === '000000') {
						uni.navigateTo({
							url: '/pages-assess/vip-pay/vip-pay?evaluateRecordId=' + this.evaluateRecordId
						})
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						});
					}
				}).catch(err => {
					console.log(err);
					uni.hideLoading();
					uni.showToast({
						title: err,
						icon: 'none'
					});
				})
			},

			///解锁当前测评
			payRecord() {
				console.log(this.evaluateRecordId)
				uni.showLoading({});
				this.$http.request({
					method: 'POST',
					url: '/eapi/operator/pay_record',
					params: {
						evaluateRecordId: this.evaluateRecordId
					}
				}).then(res => {
					console.log(res);
					uni.hideLoading();
					if (res.code === '000000') {
						///更新用户信息
						uni.$emit('event_get_user')
						this.getAssessDetail();
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				}).catch(err => {
					uni.hideLoading()
					uni.showToast({
						title: '解锁出错',
						icon: 'none'
					})
				})
			},

			compareClick() {
				if (this.paid) {
					if (this.assessList.length === 0) {
						this.getAssessList();
					} else {
						this.$refs.popupConpare.open();
					}
				}
			},
			compareHideClick() {
				this.$refs.popupConpare.close();
			},
			
			publishClick(index) {
				if (index === 1) {
					if (!this.paid) {
						return;
					}
				}
				this.grantParent();
			},
			//返回
			backClick() {
				uni.navigateBackMiniProgram({
					success(res) {
					  // 返回成功
					},
					fail(res) {
						console.log(res);
					},
				})
			},
			
			///推给家长
			grantParent() {
				console.log('grantParent');
				uni.showLoading({})
				this.$http.request({
					method: 'post',
					url: '/eapi/operator/grant_parent',
					params: {
						evaluateRecordId: this.evaluateRecordId
					}
				}).then(res => {
					console.log(res);
					uni.hideLoading()
					if (res.code === '000000') {
						uni.showToast({
							title: '推送成功',
							icon: 'none'
						})
					}else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				}).catch(err => {
					uni.hideLoading()
				})
			},

			getAssessList() {
				uni.showLoading({})
				this.$http.request({
					method: 'POST',
					url: '/eapi/operator/children_reports',
					params: {
						childrenId: this.assessDetailEntity.childrenId,
						pageNum: 0,
						pageSize: 999,
					}
				}).then(res => {
					uni.hideLoading()
					var list = []
					for (var index in res.data.content) {
						if (this.evaluateRecordId != res.data.content[index].evaluateRecordId) {
							list.push(res.data.content[index])
						}
					}
					this.assessList = list;
					if (this.assessList.length > 0) {
						this.$refs.popupConpare.open();
					} else {
						uni.showToast({
							title: '当前没有比较的测评记录',
							icon: 'none'
						})
					}
				}).catch(err => {
					uni.hideLoading()
				})
			},
		},
	}
</script>

<style lang="scss">
	uni-page-body,
	#app {
		height: 100%;
	}

	.container {
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: stretch;
		background-color: #F7F7F7;
	}

	.suggest-title {
		font-size: 36rpx;
		color: $app-font-color;
		padding-left: 40rpx;
		padding-top: 30rpx;
		padding-bottom: 30rpx;
		padding-right: 40rpx;
		background-color: #FFFFFF;
		margin-top: 20rpx;
	}

	.conclusion {
		font-size: 24rpx;
		color: $app-font-color;
		margin-top: 10rpx;
		background-color: #FFFFFF;
	}

	.scores-bar {
		background-color: #FFFFFF;
		margin-top: 20rpx;
		padding-top: 10rpx;
		padding-bottom: 10rpx;

		// height: 720upx;
	}

	.view {
		position: relative;
	}

	.suggest {
		padding-left: 10rpx;
		padding-right: 10rpx;
		font-size: 24rpx;
		color: $app-font-color;

		position: relative;
		// display: flex;
		// flex-direction: column;
		// align-items: center;
		.collapse-item-content {
			/deep/ .uni-collapse-cell__title-text {
				@include collapse-title-text-color();
			}
			/deep/ .uni-icons{
				@include collapse-title-text-color();
			}
		}
	}

	.suggest-buy {
		position: absolute;
		width: 100%;
		top: 150rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.power {
		width: 90%;
	}

	.suggest-buy-btn {
		width: 201px;
		height: 50px;
		background: linear-gradient(180deg, rgba(250, 204, 48, 1) 0%, rgba(252, 222, 122, 1) 100%);
		opacity: 1;
		border-radius: 4px;
		display: flex;
		justify-content: center;
		align-items: center;
		margin-top: 60rpx;
		color: #FFFFFF;
		font-size: 36rpx;
		font-weight: bold;

		@include assess-result-share-bg();
	}

	.mask {
		position: relative;
		filter: blur(5px);
		user-select: none;
	}

	.assess-result-share {
		width: 200rpx;
		height: 100rpx;
		background: linear-gradient(180deg, rgba(250, 204, 48, 1) 0%, rgba(252, 222, 122, 1) 100%);
		opacity: 1;
		border-radius: 4px;

		font-size: 36rpx;
		color: #FFFFFF;
		display: flex;
		justify-content: center;
		align-items: center;

		margin-top: 50rpx;
		margin-bottom: 30rpx;
		
		@include assess-result-share-bg();
	}

</style>
